package com.stars.home.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.PoiInfo
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.*
import com.baidu.mapapi.search.poi.*
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener
import com.baidu.mapapi.search.sug.SuggestionResult
import com.baidu.mapapi.search.sug.SuggestionSearch
import com.baidu.mapapi.search.sug.SuggestionSearchOption
import com.google.gson.Gson
import com.qmuiteam.qmui.kotlin.onClick
import com.stars.home.R
import com.stars.home.adapter.baidu.PoiItemAdapter
import com.stars.home.adapter.baidu.SearchDataAdapter
import com.stars.home.base.MBActivity
import com.stars.home.databinding.ActivityChoseBaiDuBinding
import com.stars.home.utils.baidu.Utils
import com.stars.home.vmodel.ChoseBaiDuVModel


/**
 * 百度地图定位
 *on 2022/9/22
 */
class ChoseBaiDuActivity : MBActivity<ChoseBaiDuVModel, ActivityChoseBaiDuBinding>(),
    OnMapStatusChangeListener, PoiItemAdapter.MyOnItemClickListener, OnGetGeoCoderResultListener,
    OnGetPoiSearchResultListener {

    // 默认逆地理编码半径范围
    private var sDefaultRGCRadius = 500
    private var mMapView: MapView? = null
    private var mBaiduMap: BaiduMap? = null
    private var mCenter: LatLng? = null
    private var mHandler: Handler? = null

    private var mRecyclerView: RecyclerView? = null

    private var mPoiItemAdapter: PoiItemAdapter? = null

    private var mGeoCoder: GeoCoder? = null

    private var mStatusChangeByItemClick = false


    //    搜索相关
    private var  cityName:String=""//默认在当前城市搜索
    private var mPoiSearch: PoiSearch? = null
    private var mLoadIndex = 0
    private var searchAdapter: SearchDataAdapter? = null
    private var old:String=""



    //选择的数据
    var   chosepoiInfo:PoiInfo?=null




    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        titleBar()?.tvRight?.visibility=View.VISIBLE
        titleBar()?.tvRight?.text="确定"
        titleBar()?.tvRight?.setTextColor(Color.parseColor("#59C2A3"))

        initRecyclerView()
        mHandler = Handler(this.mainLooper)
        initMap()
        //初始化搜索
        mPoiSearch = PoiSearch.newInstance()
        mPoiSearch?.setOnGetPoiSearchResultListener(this)


        searchAdapter=SearchDataAdapter()
        binding.searchList.adapter=searchAdapter

        searchAdapter?.setOnItemClickListener { adapter, view, position ->

            toast("点击了")
            var  data:PoiInfo= adapter.getItem(position) as PoiInfo
            binding.searchList.visibility=View.GONE
            //移动地图
            val latLng = data.getLocation()
            val mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng)
            mBaiduMap!!.setMapStatus(mapStatusUpdate)

        }



    }

    override fun listeners() {
        super.listeners()

        titleBar()?.tvRight?.onClick {

            if(null==chosepoiInfo){
                toast("请选择数据")
                return@onClick
            }

            val intent = Intent()
            var bundle = Bundle()
            bundle.putString("bean", Gson().toJson(chosepoiInfo))
            intent.putExtras(bundle)
            setResult(Activity.RESULT_OK, intent)
            finish()

        }


        binding.poi.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s!!.isEmpty() && View.VISIBLE == binding.searchList!!.visibility) {
                    binding.searchList!!.visibility = View.INVISIBLE
                }
            }

            override fun afterTextChanged(s: Editable?) {

                // 获取检索关键字
                val keyWordStr: String = binding.poi.text.toString()
                if (TextUtils.isEmpty(keyWordStr)) {
                    return
                }
                if(old==keyWordStr){
                    return
                }
                old=keyWordStr
                if (View.VISIBLE == mRecyclerView!!.visibility) {
                    binding.searchList!!.visibility = View.INVISIBLE
                }
                //去搜索
                mPoiSearch?.searchInCity(
                    PoiCitySearchOption()
                        .city(cityName)
                        .keyword(keyWordStr)
                        .pageNum(mLoadIndex) // 分页编号
                        .cityLimit(true)
                        .scope(1)
                )



            }

        })

//        binding.btnSearch.onClick {
//            //去搜索
//
//            var poi = binding.poi.text.toString().trim()
//            if (TextUtils.isEmpty(poi)) {
//                toast("请输入要搜索的关键字")
//                return@onClick
//            }
//            //影藏软键盘
//            Utils.hideKeyBoard(this@ChoseBaiDuActivity)
//            //去搜索
//            mPoiSearch?.searchInCity(
//                PoiCitySearchOption()
//                    .city(cityName)
//                    .keyword(poi)
//                    .pageNum(mLoadIndex) // 分页编号
//                    .cityLimit(true)
//                    .scope(1)
//            )
//
//        }







    }


    private fun initMap() {
        mMapView = binding.mapview
        if (null == mMapView) {
            return
        }
        mBaiduMap = mMapView!!.map
        if (null == mBaiduMap) {
            return
        }
        //获取当前位置

        val mLocClientOne = LocationClient(this)
        mLocClientOne.registerLocationListener(object : BDAbstractLocationListener() {
            override fun onReceiveLocation(location: BDLocation?) {

                if (null == location || null == mBaiduMap) {
                    return
                }
//                val latLng = LatLng(location.latitude, location.longitude)
                //设置搜索的城市-定位到当前自己所在的城市
                var city = location.city
                cityName=city

                mCenter = LatLng(location.latitude, location.longitude)
                val mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(mCenter, 16f)
                mBaiduMap!!.setMapStatus(mapStatusUpdate)
                mBaiduMap!!.setOnMapStatusChangeListener(this@ChoseBaiDuActivity)
                mBaiduMap!!.setOnMapLoadedCallback {
                    createCenterMarker()
                    reverseRequest(mCenter)
                }
                createCenterMarker()

            }

        })
        val locationClientOption = LocationClientOption()
        // 可选，设置定位模式，默认高精度 LocationMode.Hight_Accuracy：高精度；
        locationClientOption.locationMode = LocationClientOption.LocationMode.Hight_Accuracy
        // 可选，设置返回经纬度坐标类型，默认GCJ02
        locationClientOption.setCoorType("bd09ll")
        // 如果设置为0，则代表单次定位，即仅定位一次，默认为0
        // 如果设置非0，需设置1000ms以上才有效
        locationClientOption.setScanSpan(0)
        // 设置是否进行单次定位，单次定位时调用start之后会默认返回一次定位结果
        locationClientOption.setOnceLocation(true)
        //可选，设置是否使用gps，默认false
        locationClientOption.isOpenGps = true
        // 可选，是否需要地址信息，默认为不需要，即参数为false
        // 如果开发者需要获得当前点的地址信息，此处必须为true
        locationClientOption.setIsNeedAddress(true)
        // 设置定位参数
        mLocClientOne.setLocOption(locationClientOption)
        // 开启定位
        mLocClientOne.start()


    }

//    /**
//     * 添加marker
//     * @param latLng
//     */
//    private fun addOneLocMarker(latLng: LatLng) {
//        if (null != mOneLocMarker) {
//            mOneLocMarker?.remove()
//        }
//        val markerOptions = MarkerOptions()
//        val bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_binding_point)
//            ?: return
//        markerOptions.position(latLng)
//        markerOptions.icon(bitmapDescriptor)
//        mOneLocMarker = mBaiduMap!!.addOverlay(markerOptions) as Marker
//    }

    /**
     * 逆地理编码请求
     *
     * @param latLng
     */
    private fun reverseRequest(latLng: LatLng?) {
        if (null == latLng) {
            return
        }
        val reverseGeoCodeOption = ReverseGeoCodeOption().location(latLng)
            .newVersion(1) // 建议请求新版数据
            .radius(sDefaultRGCRadius)
        if (null == mGeoCoder) {
            mGeoCoder = GeoCoder.newInstance()
        }
        mGeoCoder!!.setOnGetGeoCodeResultListener(this)
        mGeoCoder!!.reverseGeoCode(reverseGeoCodeOption)
    }


    /**
     * 创建地图中心点marker
     */
    private fun createCenterMarker() {
        val projection = mBaiduMap!!.projection ?: return
        val point = projection.toScreenLocation(mCenter)
        val bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_binding_point)
            ?: return
        val markerOptions = MarkerOptions()
            .position(mCenter)
            .icon(bitmapDescriptor)
            .flat(false)
            .fixedScreenPosition(point)
        mBaiduMap!!.addOverlay(markerOptions)
        bitmapDescriptor.recycle()
    }


    /**
     * 初始化recyclerView
     */
    private fun initRecyclerView() {
        mRecyclerView = binding.poiList
        if (null == mRecyclerView) {
            return
        }
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        mRecyclerView!!.layoutManager = layoutManager
    }


    override fun onResume() {
        super.onResume()
        if (null != mMapView) {
            mMapView!!.onResume()
        }


    }

    override fun onPause() {
        super.onPause()
        if (null != mMapView) {
            mMapView!!.onPause()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != mHandler) {
            mHandler!!.removeCallbacksAndMessages(null)
        }

        if(null!=mPoiSearch){
            mPoiSearch?.destroy()

        }
        if (null != mGeoCoder) {
            mGeoCoder!!.destroy()
        }

        if (null != mMapView) {
            mMapView!!.onDestroy()
        }

    }


    override fun vmClass(): Class<ChoseBaiDuVModel> {
        return ChoseBaiDuVModel::class.java
    }

    override fun binding(): ActivityChoseBaiDuBinding {
        return ActivityChoseBaiDuBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return "选择地点"
    }

    /**
     * 更新UI
     *
     * @param reverseGeoCodeResult
     */
    private fun updateUI(reverseGeoCodeResult: ReverseGeoCodeResult) {
        var poiInfos = reverseGeoCodeResult.poiList
        val curAddressPoiInfo = PoiInfo()
       curAddressPoiInfo.address = reverseGeoCodeResult.address
        curAddressPoiInfo.location = reverseGeoCodeResult.location
        if (null == poiInfos) {
            poiInfos = ArrayList(2)
        }
        poiInfos.add(0, curAddressPoiInfo)

        chosepoiInfo= poiInfos[0]//默认选择第一个
        if (null == mPoiItemAdapter) {
            mPoiItemAdapter = PoiItemAdapter(poiInfos)
            mRecyclerView!!.adapter = mPoiItemAdapter
            mPoiItemAdapter!!.setOnItemClickListener(this)
        } else {
            mPoiItemAdapter!!.updateData(poiInfos)
        }
    }


    override fun onMapStatusChangeStart(p0: MapStatus?) {
    }

    override fun onMapStatusChangeStart(p0: MapStatus?, p1: Int) {
    }

    override fun onMapStatusChange(p0: MapStatus?) {
    }

    override fun onMapStatusChangeFinish(mapStatus: MapStatus?) {
        val newCenter: LatLng = mapStatus!!.target

        // 如果是点击poi item导致的地图状态更新，则不用做后面的逆地理请求，

        // 如果是点击poi item导致的地图状态更新，则不用做后面的逆地理请求，
        if (mStatusChangeByItemClick) {
            if (!Utils.isLatlngEqual(mCenter, newCenter)) {
                mCenter = newCenter
            }
            mStatusChangeByItemClick = false
            return
        }

        if (!Utils.isLatlngEqual(mCenter, newCenter)) {
            mCenter = newCenter
            reverseRequest(mCenter)
        }
    }

    override fun onGetGeoCodeResult(p0: GeoCodeResult?) {
    }

    override fun onGetReverseGeoCodeResult(reverseGeoCodeResult: ReverseGeoCodeResult?) {
        if (null == reverseGeoCodeResult) {
            return
        }

        mHandler!!.post { updateUI(reverseGeoCodeResult) }
    }

    override fun onItemClick(position: Int, poiInfo: PoiInfo?) {
        if (poiInfo?.getLocation() == null) {
            return
        }
        chosepoiInfo= poiInfo
//        Log.e("-info-", "chosepoiInfo=: "+chosepoiInfo?.getLocation()?.latitude+"/"+chosepoiInfo?.getLocation()?.longitude )

        mStatusChangeByItemClick = true
        val mapStatusUpdate = MapStatusUpdateFactory.newLatLng(poiInfo.getLocation())
        mBaiduMap!!.setMapStatus(mapStatusUpdate)
    }

    //搜索相关
    override fun onGetPoiResult(poiResult: PoiResult?) {
        if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            mLoadIndex = 0
            toast("未找到结果")
            return
        }
        var poiInfos:ArrayList<PoiInfo> = poiResult.allPoi as ArrayList<PoiInfo>
        if(null==poiInfos ){
            toast("没有数据")
            return
        }

        binding.searchList.visibility=View.VISIBLE
        searchAdapter?.clearList()
        searchAdapter?.setList(poiInfos)

    }

    override fun onGetPoiDetailResult(p0: PoiDetailResult?) {
    }

    override fun onGetPoiDetailResult(p0: PoiDetailSearchResult?) {
    }

    override fun onGetPoiIndoorResult(p0: PoiIndoorResult?) {
    }



}
